package com.ucw.mountain.search;

import java.util.List;

public class PageSearch extends BaseSearch {

	/**
	 * 总条数
	 */
	private int total;
	/**
	 * 当前第几页
	 */
	private int page;
	/**
	 * 总页数
	 */
	private int totalPage;
	/**
	 * 每页显示条数
	 */
	private int perPage = 5;
	/**
	 * 数据库中limit的参数，从第几条开始取
	 */
	private transient int dbIndex;
	/**
	 * 数据库中limit的参数，一共取多少条
	 */
	private transient int dbNumber;

	/**
	 * 根据当前对象中属性值计算并设置相关属性值
	 */
	private void count() {
		// 计算总页数
		int totalPageTemp = this.total / this.perPage;
		int plus = (this.total % this.perPage) == 0 ? 0 : 1;
		totalPageTemp = totalPageTemp + plus;
		if (totalPageTemp <= 0) {
			totalPageTemp = 1;
		}
		this.totalPage = totalPageTemp;

		// 设置当前页数
		// 总页数小于当前页数，应将当前页数设置为总页数
		if (this.totalPage < this.page) {
			this.page = this.totalPage;
		}
		// 当前页数小于1设置为1
		if (this.page < 1) {
			this.page = 1;
		}

		// 设置limit的参数
		this.dbIndex = (this.page - 1) * this.perPage;
		this.dbNumber = this.perPage;
	}

	public int getTotal() {
		return total;
	}

	public void setTotal(int total) {
		this.total = total;
		this.count();
	}

	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}

	public int getTotalPage() {
		return totalPage;
	}

	public void setTotalPage(int totalPage) {
		this.totalPage = totalPage;
	}

	public int getPerPage() {
		return perPage;
	}

	public void setPerPage(int perPage) {
		this.perPage = perPage > 0 ? perPage : 1;
	}

	public int getDbIndex() {
		return dbIndex;
	}

	public void setDbIndex(int dbIndex) {
		this.dbIndex = dbIndex;
	}

	public int getDbNumber() {
		return dbNumber;
	}

	public void setDbNumber(int dbNumber) {
		this.dbNumber = dbNumber;
	}

	public <T> PageInfo<T> getPageInfo(List<T> data) {

		return new PageInfo<T>(getPage(), getPerPage(), getTotal(), getTotalPage(), data);
	}

	public static class PageInfo<T> {
		/**
		 * 页码
		 */
		private int page;
		/**
		 * 每页数量
		 */
		private int perPage;
		/**
		 * 总共数量
		 */
		private int total;

		/**
		 * 总共页数
		 * 
		 */
		private int totalPage;
		/**
		 * 数据
		 */
		private List<T> data;

		public PageInfo() {
		}

		public PageInfo(int page, int perPage, int total, int totalPage, List<T> data) {
			super();
			this.page = page;
			this.perPage = perPage;
			this.total = total;
			this.totalPage = totalPage;
			this.data = data;
		}

		public int getPage() {
			return page;
		}

		public int getPerPage() {
			return perPage;
		}

		public int getTotal() {
			return total;
		}

		public int getTotalPage() {
			return totalPage;
		}

		public List<T> getData() {
			return data;
		}

		public void setData(List<T> data) {
			this.data = data;
		}

	}
}
